import React, { Component } from 'react';
import {
	StyleSheet, Text, TouchableOpacity,
	PixelRatio, View, Image, ScrollView, TextInput
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { FormItem } from '../../../components/form/formItem';
import { orderBaseStyle } from './_common/style.js';
import Dictionary from '../../../utils/dictionary';
import { RadiusGroupCpt } from './_components/RadiusGroupCpt';
import DateGapPicker from '../../../components/common/DateGapPicker';
import ToastUtil from '../../../utils/toast';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
import { Loading } from '../../../component/page-status/Pageloading';

const scale = GLOBAL.SCALE;

export class relevanceAddPage extends Component {
	static navigationOptions = ({ navigation }) => {
		return {
			headerTitle: '销售意向关联',
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: {  // 头部整体样式 
				elevation: 0,
				backgroundColor: '#f7f7f7',
				borderBottomWidth: 0
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};


	constructor(props) {
		super(props);
		this.state = {
			inPayType: null,
			openDatePicker: false,
			loading: false
		}
		this.inPayTypeData = []; // 内贸付款类型
		this.orderRptInfo = this.props.navigation.state.params.orderRptInfo;
		console.log('this.orderRptInfo', this.orderRptInfo);
		this.sendData = {
			goodsId: this.orderRptInfo.goodsId,
			goodsName: this.orderRptInfo.goodsName,
			totalQuantity: this.orderRptInfo.totalQuantity,
			uomName: this.orderRptInfo.uomName,
			price: this.orderRptInfo.price,
			planSellQuantity: null,
			planSellPrice: null,
			planGrossProfit: null,
			companyName: '',
			companyAddress: '',
			planRecvType: '',
			planRecvTypeName: '',
			planSellBeginDate: '',
			planSellEndDate: '',
		};
	}

	componentWillMount () {
		this._getDictList();
		this._getLatestPrice();
	}

	// 获取当日现货价
	async _getLatestPrice () {
		let responseData = await HTTP.POST(API_GENERATE(API.GET_LATEST_PRICE), { goodsId: this.orderRptInfo.goodsId });
		if (responseData) {
			let { suggestedPrice } = responseData;
			this.suggestedPrice = suggestedPrice;
			this.setState({
				ls: true
			})
		}
	}

	//获取数据库字典
	async _getDictList () {
		this.inPayTypeData = await Dictionary.get('EC_PAY_TYPE'); // 付款类型
		this.setState({
			ls: true
		})
	}

	//选择付款类型回调
	_radiusItemFn = (itemData, id, indexKey) => {
		this.sendData.planRecvType = this.inPayTypeData[indexKey].dictKey;
		this.sendData.planRecvTypeName = this.inPayTypeData[indexKey].dictName;

	}

	// 添加按钮
	_addFn = () => {
		if (this.state.loading) { return; }
		this.setState({ loading: true });
		const { companyId, companyAddressId, planSellBeginDate, planSellEndDate, planRecvType, planSellQuantity, planSellPrice } = this.sendData;
		if (!companyId) {
			this.setState({ loading: false });

			ToastUtil.showWarning('请选择客户');
			return false;
		}
		if (!planSellQuantity) {
			this.setState({ loading: false });

			ToastUtil.showWarning('请输入销售量');
			return false;
		}
		if (!planSellPrice) {
			this.setState({ loading: false });

			ToastUtil.showWarning('请输入销售价');
			return false;
		}
		if (!planRecvType) {
			this.setState({ loading: false });

			ToastUtil.showWarning('请选择收款类型');
			return false;
		}
		if (!companyAddressId) {
			this.setState({ loading: false });

			ToastUtil.showWarning('请选择收货地');
			return false;
		}
		if (!planSellBeginDate || !planSellEndDate) {
			this.setState({ loading: false });

			ToastUtil.showWarning('请选择交货时间');
			return false;
		}
		this.setState({ loading: false });
		this.props.navigation.state.params.callBack(this.sendData);
		this.props.navigation.goBack();
	}

	//选择供应商/客户
	_providerFn = () => {
		let params = {
			orderType: 'S',
			queryType: 'ORDER_ADD',
			type: 'relevanceAddPage',
			callBack: (selectData) => { this._providerCb(selectData) }
		}
		this.props.navigation.navigate('SeachSupplierPage', params)
	}

	//选择供应商/客户-返回数据
	_providerCb = async (selectData) => {
		let { companyName, companyId } = selectData;
		if (this.sendData.companyId !== companyId) {
			this.sendData.companyId = companyId;
			this.sendData.companyName = companyName;
			this.sendData.companyAddressId = '';
			this.sendData.companyAddress = '';
			this.setState({ ls: true })
		}
	}

	//选择收货地址
	_endAddressFn = () => {
		if (!this.sendData.companyId) {
			ToastUtil.showWarning('请先选择企业')
			return
		}
		let params = {
			companyId: this.sendData.companyId,
			companyName: this.sendData.companyName,
			orderType: 'S',
			deliveryType: 'P',
			addressType: 'destAddressId',  // destAddressId  ->  目的地   srcAddressId ->  出库地
			getAddressCallBack: (data) => {
				this._endAddressCb(data)
			}
		};
		this.props.navigation.navigate('DeliveryAddress', params);
	}

	//选择收货地址-返回数据
	_endAddressCb = async (selectData) => {
		if (this.sendData.companyAddressId !== selectData[0].addrId) {
			this.sendData.companyAddressId = selectData[0].addrId;
			this.sendData.companyAddress = selectData[0].addressName;
			this.setState({ ls: true })
		}
	}

	//点击交货时间
	_clickShow = () => {
		this.setState({
			openDatePicker: true
		})
	}
	/* 点击交货时间回调 */
	_planDataCall = (planData) => {
		this.sendData.planSellBeginDate = planData.startDate;
		this.sendData.planSellEndDate = planData.endDate;
		this.setState({ ls: true })
	}

	//填写回调
	_writeCallBack = (objData) => {
		let keyStr = objData.type;
		if (keyStr) {
			this.sendData.planSellPrice = parseFloat(objData.value);
		} else {
			this.sendData.planSellQuantity = parseFloat(objData.value);
		}
	}

	//键盘弹出遮挡问题
	scrollViewTo (e) {
		let target = e.nativeEvent.target;
		let scrollLength = 0;//初始值  
		if (target === ReactNative.findNodeHandle(this.refs.textarea)) {
			scrollLength = 216;
		}
		this.refs.scroll.scrollTo({ y: scrollLength, x: 0 });
	}

	render () {
		let { inPayType, openDatePicker, loading } = this.state;
		const { companyName, companyAddress, price, planSellBeginDate, planSellEndDate, planSellQuantity, planSellPrice, planRecvType } = this.sendData;
		let dateObj = {
			startDate: planSellBeginDate || null,
			endDate: planSellEndDate || null
		};

		return (
			<View style={styles.container}>
				<ScrollView
					style={{ paddingBottom: 50 * scale }}
					ref='scroll'
					showsVerticalScrollIndicator={false}
					keyboardShouldPersistTaps={true}
				>
					<View style={styles.body} onStartShouldSetResponderCapture={(e) => {
						let target = e.nativeEvent.target;
						if (target !== ReactNative.findNodeHandle(this.refs.textarea)) {
							this.refs.textarea.blur();
						}
					}}>
						<FormItem handleCallBack={this._providerFn} required={true} value={companyName} type="select" label="客户名称" placeHolder={'请选择客户'} />

						<FormItem keyboardType={'numeric'} handleCallBack={(text) => { this._writeCallBack({ type: 0, value: text }) }} value={planSellQuantity} labelStyle={styles.labelStyle} required={true} placeHolder={'请输入'} label={'销售量'} rightText={'吨'} type={'input'} />
						<FormItem keyboardType={'numeric'} handleCallBack={(text) => { this._writeCallBack({ type: 1, value: text }) }} value={planSellPrice} labelStyle={styles.labelStyle} required={true} placeHolder={'请输入'} label={'销售价'} rightText={'元/吨'} type={'input'} />
						<Text style={styles.price}>今日现货价: {(this.suggestedPrice || 0).toFixed(2) || 0} 元/吨</Text>
						<RadiusGroupCpt data={{
							title: '收款类型',
							required: true,
							listData: this.inPayTypeData,
							selectedKey: planRecvType,
							_radiusItemFn: this._radiusItemFn,
							textStyleBox: orderBaseStyle.textStyle,
							id: 'inPayType'
						}} />
						<FormItem handleCallBack={this._endAddressFn} required={true} type="select" label="目的地" />
						<Text style={orderBaseStyle.address}>{companyAddress || '请选择目的地'}</Text>

						<View style={styles.boxUp}>
							<Text style={styles.label}><Text style={styles.require}>* </Text>交货时间</Text>
							<TouchableOpacity style={styles.rowStyle} onPress={this._clickShow}>
								<Text style={styles.xian}>{planSellBeginDate}</Text>
								<Text>至</Text>
								<Text style={styles.xian}>{planSellEndDate}</Text>
							</TouchableOpacity>
						</View>

						<Text style={styles.tearText}>资源平衡 (客户需求) 及市场简要分析</Text>
						<TextInput
							multiline={true}
							style={styles.notgoodInput}
							placeholder={'请输入…'}
							placeholderTextColor={"#999"}
							onChangeText={(text) => {
								this.sendData.planRemark = text;
							}}
							ref='textarea'
							onFocus={this.scrollViewTo.bind(this)}
							onEndEditing={() => { this.refs.scroll.scrollTo({ y: 0, x: 0, animated: true }) }} />
					</View>
				</ScrollView>
				<View style={styles.btnBox}>
					<Text style={styles.btnText} onPress={() => { this._addFn() }}>添加</Text>
				</View>

				<DateGapPicker
					isVisible={openDatePicker}
					date={dateObj}
					double={true}
					cb={(newDate) => {
						if (!newDate) return;
						this.setState({ openDatePicker: false }, () => {
							this._planDataCall(newDate)
						})
					}} />

				{
					loading ? (<View style={orderBaseStyle.statusStyle}><Loading /></View>) : null
				}
			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#f7f7f7',
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale
	},
	body: {
		backgroundColor: style.color.white,
		width: '100%',
		borderRadius: 4 * scale,
		paddingTop: 15 * scale,
		paddingBottom: 10 * scale,
	},
	boxUp: {
		flexDirection: 'row',
		paddingTop: 15 * scale,
		paddingLeft: 13 * scale
	},
	label: {
		width: 70 * scale,
		marginRight: 20 * scale,
		color: '#333',
	},
	require: {
		fontSize: 14 * scale,
		color: '#D0021B',
	},
	xian: {
		width: 80 * scale,
		height: 24 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderColor: '#ccc',
		marginLeft: 5 * scale,
		marginRight: 5 * scale,
	},
	inputxian: {
		paddingVertical: 0,
		textAlign: 'center'
	},
	tearText: {
		fontSize: 14 * scale,
		paddingLeft: 13 * scale,
		paddingTop: 25 * scale,
		color: '#333',
	},
	notgoodInput: {
		marginLeft: 13 * scale,
		marginRight: 13 * scale,
		marginTop: 8 * scale,
		height: 90 * scale,
		lineHeight: 24 * scale,
		borderWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderColor: style.color.gray,
	},
	price: {
		color: '#999',
		textAlign: 'right',
		fontSize: 12 * scale,
		marginTop: -5 * scale,
		paddingRight: 24.5 * scale
	},
	labelStyle: {
		fontSize: 14 * scale,
		color: '#333',
	},
	btnText: {
		width: '80%',
		height: 40 * scale,
		lineHeight: 40 * scale,
		color: style.color.white,
		textAlign: 'center',
		backgroundColor: style.color.themeColor,
		marginLeft: '10%',
		borderRadius: 4 * scale,
		marginBottom: 15 * scale,
		textAlignVertical: 'top'
	},
	rowStyle: {
		flexDirection: 'row',
	},
})